package cc.rengu.igas.bsps.common.dao.impl;

import cc.rengu.igas.bsps.common.dao.BspsUserInfoMapper;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.common.enums.UserStatusEnum;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.utility.util.*;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息表.
 */
public class BspsUserInfoMapperImpl implements BspsUserInfoMapper {
    private RgLogger rglog = RgLog.getLogger(this.getClass().getName());
    private String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppParamConstant.DATABASE_CONF_NODE, AppConfigConstant.OLTP_POOL_NAME);


    @Override
    public UserInfo selectBspsUserInfoByUserId(String instId, String userId) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectBspsUserInfoByUserId");
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setInstId(instId);
        userInfo.setUserStatus(UserStatusEnum.NOMAL.getStatus());
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, userInfo, userInfo);
        if (0 != iReturnCode) {
            rglog.error("根据机构号<{}>, userId:<{}>查询用户信息失败！", instId, userId);
            return null;
        }
        return userInfo;
    }

    @Override
    public UserInfo selectBspsUserInfoByUserLoginId(String instId, String userLoginId) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectBspsUserInfoByUserLoginId");
        UserInfo userInfo = new UserInfo();
        userInfo.setUserLoginId(userLoginId);
        userInfo.setInstId(instId);
        userInfo.setUserStatus(UserStatusEnum.NOMAL.getStatus());

        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, userInfo, UserInfo.class);
        if (null == objectList || objectList.isEmpty()) {
            rglog.error("根据机构号<{}>, userLoginId:<{}>查询用户信息失败！", instId, userLoginId);
            return null;
        }
        List<UserInfo> userInfos = objectList.stream().map(item -> (UserInfo) item).collect(Collectors.toList());
        if (userInfos.size() > 1) {
            rglog.error("根据机构号<{}>, openId:<{}>查询用户信息失败！", instId, userLoginId);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        userInfo = userInfos.get(0);
        return userInfo;
    }

    @Override
    public UserInfo selectBspsUserInfoByOpenId(String instId, String openId) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectBspsUserInfoByOpenId");
        UserInfo userInfo = new UserInfo();
        userInfo.setOpenId(openId);
        userInfo.setInstId(instId);
        userInfo.setUserStatus(UserStatusEnum.NOMAL.getStatus());

        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, userInfo, UserInfo.class);
        if (null == objectList || objectList.isEmpty()) {
            rglog.error("根据机构号<{}>, openId:<{}>查询用户信息失败！", instId, openId);
            return null;
        }
        List<UserInfo> userInfos = objectList.stream().map(item -> (UserInfo) item).collect(Collectors.toList());
        if (userInfos.size() > 1) {
            rglog.error("根据机构号<{}>, openId:<{}>查询用户信息失败！", instId, openId);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        userInfo = userInfos.get(0);
        return userInfo;
    }

    @Override
    public UserInfo selectBspsUserInfoByUserMobileId(String instId, String userMobileId) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectBspsUserInfoByUserMobileId");
        UserInfo userInfo = new UserInfo();
        userInfo.setMobileNo(userMobileId);
        userInfo.setInstId(instId);
        userInfo.setUserStatus(UserStatusEnum.NOMAL.getStatus());
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, userInfo, userInfo);
        if (0 != iReturnCode) {
            rglog.error("根据机构号<{}>, userMobileId:<{}>查询用户信息失败！", instId, userMobileId);
            return null;
        }
        return userInfo;
    }

    @Override
    public int updateBspsUserErrorTimeByPrimaryKey(UserInfo userInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updateBspsUserErrorTimesByPrimaryKey");
        userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, userInfo, null);
        if (0 != iReturnCode) {
            rglog.error("更新用户登录次数信息失败,iReturnCode:<{}>", iReturnCode);
            return iReturnCode;
        }
        return iReturnCode;
    }

    @Override
    public int updateBspsOpenIdByPrimaryKey(UserInfo userInfo, String openId) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updateBspsOpenIdByPrimaryKey");
        userInfo.setOpenId(openId);
        userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        int iReturnCode = dbsUtil.dbsExecuteTransactionSql(sqlStr, userInfo, null);
        if (0 != iReturnCode) {
            rglog.error("更新用户登录次数信息失败,iReturnCode:<{}>", iReturnCode);
            return iReturnCode;
        }
        return iReturnCode;
    }

    /**
     * 根据手机号查询用户列表信息
     *
     * @param instId   机构号
     * @param mobileNo 手机号
     * @return 用户信息
     * @throws Exception 异常
     */
    @Override
    public List<UserInfo> selectBspsUserInfoListByMobileNo(String instId, String mobileNo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "selectBspsUserInfoListByMobileNo");
        UserInfo userInfo = new UserInfo();
        userInfo.setInstId(instId);
        userInfo.setMobileNo(mobileNo);
        userInfo.setUserStatus(UserStatusEnum.NOMAL.getStatus());
        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, userInfo, UserInfo.class);
        if (null == objectList || objectList.isEmpty()) {
            rglog.error("根据机构号<{}>，用户手机号<{}>获取用户信息失败!", instId, mobileNo);
            return null;
        }
        return objectList.stream().map(item -> (UserInfo) item).collect(Collectors.toList());
    }

    @Override
    public int insertBspsUserInfo(UserInfo userInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        if (StringUtil.isEmptyOrNull(userInfo.getUserLoginId())) {
            userInfo.setUserLoginId("LOGINID");
        }
        if (StringUtil.isEmptyOrNull(userInfo.getOpenId())) {
            userInfo.setOpenId("OPENID");
        }
        if (StringUtil.isEmptyOrNull(userInfo.getUserMobileId())) {
            userInfo.setUserMobileId("MOBILEID");
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "insertBspsUserInfo");
        int iReturnCode = dbsUtil.dbsExecuteTransactionSql(sqlStr, userInfo, null);
        if (0 != iReturnCode) {
            rglog.error("登记用户信息表失败,iReturnCode:<{}>", iReturnCode);
            return iReturnCode;
        }
        return iReturnCode;
    }


    @Override
    public int updateBspsPasswordByUserLoginId(String instId, String userLoginId, String password, String passwordType) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        UserInfo userInfo = new UserInfo();
        userInfo.setInstId(instId);
        userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        int iReturnCode = -1;
        if ("00".equals(passwordType)) {
            userInfo.setUserLoginId(userLoginId);
            userInfo.setLoginPassword(password);
            String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updateBspsLoginPasswordByUserLoginId");
            iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, userInfo, null);
            if (0 != iReturnCode) {
                rglog.error("登记用户信息表失败,iReturnCode:<{}>", iReturnCode);
                return iReturnCode;
            }

        } else if ("01".equals(passwordType)) {
            userInfo.setUserId(userLoginId);
            userInfo.setTransPassword(password);
            String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updateBspsTransPasswordByUserId");
            iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, userInfo, null);
            if (0 != iReturnCode) {
                rglog.error("登记用户信息表失败,iReturnCode:<{}>", iReturnCode);
                return iReturnCode;
            }
        } else {
            //异常
            rglog.error("密码类型异常, passwordType:<{}>", passwordType);
            return -1;
        }
        return iReturnCode;
    }

    @Override
    public int updateBspsUserInfoByPrimaryKey(UserInfo userInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updateBspsUserInfoByPrimaryKey");
        int iReturnCode = dbsUtil.dbsExecuteTransactionSql(sqlStr, userInfo, null);
        if (0 != iReturnCode) {
            rglog.error("更新用户信息表失败,iReturnCode:<{}>", iReturnCode);
            return iReturnCode;
        }
        return iReturnCode;
    }

    public int updateBspsLoginIdLoginPasswordByUserId(String instId, String userLoginId, String password, String userId) throws Exception {
        UserInfo userInfo = new UserInfo();
        userInfo.setInstId(instId);
        userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        userInfo.setUserId(userId);
        userInfo.setUserLoginId(userLoginId);
        userInfo.setLoginPassword(password);
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updateBspsLoginIdLoginPasswordByUserId");
        int iReturnCode = -1;
        iReturnCode = dbsUtil.dbsExecuteTransactionSql(sqlStr, userInfo, null);
        if (0 != iReturnCode) {
            rglog.error("登记用户信息表失败,iReturnCode:<{}>", iReturnCode);
            return iReturnCode;
        }
        return iReturnCode;
    }

    @Override
    public int updateUserStatusByPrimaryKey(String instId, String userId) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        UserInfo userInfo = new UserInfo();
        userInfo.setInstId(instId);
        userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        userInfo.setUserStatus(UserStatusEnum.CANCEL.getStatus());
        userInfo.setLastOprId(userId);
        userInfo.setUserId(userId);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updateUserStatusByPrimaryKey");
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, userInfo, null);
        if (0 != iReturnCode) {
            rglog.error("更新用户信息表失败,iReturnCode:<{}>", iReturnCode);
            return iReturnCode;
        }
        return iReturnCode;
    }

}
